package com.ruoyi.project.pay;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.Md5Utils;
import com.ruoyi.project.channel.businessInfo.domain.BusinessInfo;
import com.ruoyi.project.channel.businessInfo.service.IBusinessInfoService;
import com.ruoyi.project.channel.channelAccount.domain.ChannelAccount;
import com.ruoyi.project.channel.channelOrder.domain.ChannelOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.*;

public class Util {
    private static final Logger log = LoggerFactory.getLogger(PayServiceImpl.class);
    private static Vector<String> accountQueue = new Vector<>();

    /**
     * 过滤信息由支付类型 加 码商 加账号进行区分
     * @param accounts
     * @param payType
     * @return
     */
    public static ChannelAccount getAccount(List<ChannelAccount> accounts, String payType, String channelId) {
        for (int i = 0; i < accounts.size(); i++) {
            log.info("getAccount:" + accounts.get(i).getAccount());
            ChannelAccount channelAccount = accounts.get(i);
            if (accountQueue.contains(payType + "_" + channelId + "_" + channelAccount.getAccount())) {
                // 如果包含这个账号说明已经出过码了
                continue;
            } else {
                // 没匹配过
                // 09_1333333333333
                accountQueue.add(payType + "_" + channelId + "_" + channelAccount.getAccount());
                return channelAccount;
            }
        }
        // 如果上面还没匹配到 说明都出过码了 得重新开始 默认选第一个
        // 把账号队列里面的这种类型的账号全部删除 重新开始排队
        Vector<String> tmp = new Vector<>();
        for (int j = 0; j < accountQueue.size(); j++) {
            String key = accountQueue.get(j);
            if (key.startsWith(payType + "_" + channelId + "_" )) {
                tmp.add(key);
            }
        }
        accountQueue.removeAll(tmp);
        accountQueue.add(payType + "_" + channelId + "_" + accounts.get(0).getAccount());
        return accounts.get(0);
    }


    public static String getMd5Sign(IBusinessInfoService businessInfoService, ChannelOrder channelOrder, String time) {
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(channelOrder.getBusinessId());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("childOrderno=").append(channelOrder.getChildOrderno());
        stringBuilder.append("&payAmount=").append(parseNullString(channelOrder.getPayAmount() + ""));
        stringBuilder.append("&orderStatus=").append("1");
        stringBuilder.append("&time=").append(time);
        stringBuilder.append("&").append(businessInfo.getApiKey());
        String sign = "";
        try {
            log.info("setToPreOrder:" + stringBuilder.toString());
            sign = Md5Utils.androidMD5(stringBuilder.toString());
            log.info("sign:" + sign);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return sign;
    }

    public static String getMd5SignSH(IBusinessInfoService businessInfoService, ChannelOrder channelOrder) {
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(channelOrder.getBusinessId());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("customerid=").append(channelOrder.getBusinessId() + "");
        stringBuilder.append("&status=").append("1");
        stringBuilder.append("&sdpayno=").append(parseNullString(channelOrder.getPtOrderno()));
        stringBuilder.append("&sdorderno=").append(parseNullString(channelOrder.getChildOrderno()));
        stringBuilder.append("&total_fee=").append(channelOrder.getPayAmount());
        stringBuilder.append("&paytype=").append(channelOrder.getPayType());
        stringBuilder.append("&").append(businessInfo.getApiKey());
        String sign = "";
        try {
            log.info("getMd5SignSH:" + stringBuilder.toString());
            sign = Md5Utils.androidMD5(stringBuilder.toString());
            log.info("sign:" + sign);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return sign;
    }

    private static String parseNullString(String value) {
        if (value == null) {
            return "";
        }
        return value;
    }

    /**
     * 编码后的url
     *
     * @param srcurl
     * @return
     */
    public static String getShortUrl(String srcurl) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String url = "http://h5ip.cn/Index/addAddress";
            String bodyValTemplate = "source=" + srcurl + "&https=1";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity entity = new HttpEntity(bodyValTemplate, headers);
            String body = restTemplate.exchange(url, HttpMethod.POST, entity, String.class).getBody();
            // {"code":0,"msg":"","source":"http:\/\/118.31.121.214\/","short_url":"http:\/\/h5ip.cn\/GgSn"}
            JSONObject result = JSONObject.parseObject(body);
            if (result.getInteger("code") == 0) {
                return result.getString("short_url").replace("\\/", "/");
            }
            return srcurl;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return srcurl;
        }
    }

    /**
     * 编码后的url
     *
     * @param srcurl
     * @return
     */
    public static String getShortUrl2(String srcurl) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://urlc.cn/api/add?longurl=" + srcurl;
        String responseMessage = restTemplate.getForObject(url, String.class);
        JSONObject data = JSONObject.parseObject(responseMessage);
        JSONObject shortData = data.getJSONObject("data");
        String shortid = shortData.getString("shortid");
        return "https://urlc.cn/" + shortid;
    }

    /**
     * 编码后的url
     *
     * @param srcurl
     * @return
     */
    public static String getShortUrl3(String srcurl) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String url = "https://www.06q.net/api/?key=n3zsqZIIoXSW&format=json&url=" + srcurl;
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity entity = new HttpEntity(headers);
            String body = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
            JSONObject result = JSONObject.parseObject(body);
            if (result.getInteger("error") == 0) {
                return result.getString("short").replace("\\/", "/");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return srcurl;
    }

    /**
     * 补位001 099
     *
     * @param ra
     * @return
     */
    public static String getRandom(int ra) {
        if (ra < 10) {
            return "00" + ra;
        } else if (ra < 100) {
            return "0" + ra;
        } else if (ra < 1000) {
            return "0" + ra;
        } else {
            return ra + "";
        }
    }

    public static String stringToUnicode(String str) {
        StringBuffer sb = new StringBuffer();
        char[] c = str.toCharArray();
        for (int i = 0; i < c.length; i++) {
            sb.append("\\u" + Integer.toHexString(c[i]));
        }
        return sb.toString();
    }

    /**
     * 排序
     * @param map
     */
    public static String sortKey(HashMap<String,String> map){
        List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
        Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
            //升序排序
            public int compare(Map.Entry<String, String> o1,
                               Map.Entry<String, String> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });
        String str = "";
        for(Map.Entry<String,String> mapping:list){
            if(mapping.getValue() == null || mapping.getValue().trim().equals("")){
                continue;
            }
            str = str + mapping.getKey() +"="+mapping.getValue()+"&";
        }
        str = str.substring(0,str.length()-1);
        return str;

    }

    /**
     * 排序
     * @param map
     */
    public static String toSignStr(HashMap<String,String> map){
        List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
        String str = "";
        for(Map.Entry<String,String> mapping:list){
            str = str + mapping.getKey() +"="+mapping.getValue()+"&";
        }
        str = str.substring(0,str.length()-1);
        return str;

    }

    /**
     * 转出json
     * @param map
     */
    public static JSONObject convetToJSON(HashMap<String,String> map){
        JSONObject jsonObject = new JSONObject();
        List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
        for(Map.Entry<String,String> mapping:list){
            jsonObject.put(mapping.getKey(),mapping.getValue() );
        }
        return jsonObject;

    }

//    public static String convertToSignStr(HashMap<String,String> map){
////        for(Map.Entry<String,String> mapping:list){
////            System.out.println(mapping.getKey()+":"+mapping.getValue());
////        }
////    }
}
